package me.cloudcat.develop.service.process;

import java.util.List;
import java.util.Map;

import org.activiti.engine.HistoryService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = false)
public class ProcessService {

	@Autowired
	ProcessEngine engine;

	@Autowired
	RepositoryService repositoryService;

	@Autowired
	TaskService taskService;

	@Autowired
	HistoryService historyService;
	
	@Autowired
	RuntimeService runtimeService;

	/**
	 * 部署流程定义
	 * 
	 * @param processName
	 * @param variables
	 */
	public void deployProcess(String processName, Map<String, Object> variables) {
		if (processName == null)
			throw new RuntimeException("流程名为空！");
		Deployment deployment = repositoryService.createDeployment()
				.addClasspathResource("diagram/parallelGateWay.bpmn").name(processName).deploy();
		System.out.println("部署的ID：" + deployment.getId());
	}

	/**
	 * 查询单个部署
	 * 
	 * @param deploymentId
	 */
	public Deployment getDeployment(String deploymentId) {
		Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).list().get(0);
		return deployment;
	}

	/**
	 * 查询所有部署
	 * 
	 */
	public List<Deployment> getDeployment() {
		List<Deployment> list = repositoryService.createDeploymentQuery().list();
		return list;
	}

	/**
	 * 使用不同的方式（method）来查询查询单个流程实例
	 * 
	 * @param deploymentId
	 */
	public ProcessDefinition getProcess(String arg, String method) {
		ProcessDefinition processDefinition;
		if (method.trim().equals("defId")) {
			processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(arg).list().get(0);
		} else if (method.trim().equals("deployId")) {
			processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(arg).list().get(0);
		} else if (method.trim().equals("key")) {
			processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionKey(arg).list()
					.get(0);
		} else {
			processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(arg).list().get(0);
		}
		return processDefinition;
	}

	/**
	 * 查询所有流程实例
	 * 
	 */
	public List<ProcessDefinition> getProcess() {
		List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().list();
		return list;
	} 

	/**
	 * 删除流程定义(级联删除，不管流程是否启动都删除)
	 * 
	 * @param deploymentId
	 */
	public void deleteProcess(String deploymentId) {
		repositoryService.deleteDeployment(deploymentId, true);
	}

	/**
	 * 启动流程实例
	 * 
	 * @param procDefId
	 */
	public void startProcess(String procDefId) {
//		runtimeService.startProcessInstanceById(procDefId);
		runtimeService.startProcessInstanceByKey(procDefId,"1");
	}

	/**
	 * 附加功能：删除流程定义（删除key相同的所有不同版本的流程定义）
	 *
	 */
	public void deleteProcessDefinitionByKey(String processDefinitionKey) {
		// 先使用流程定义的key查询流程定义，查询出所有的版本
		List<ProcessDefinition> list = repositoryService//
				.createProcessDefinitionQuery()//
				.processDefinitionKey(processDefinitionKey)// 使用流程定义的key查询
				.list();
		// 遍历，获取每个流程定义的部署ID
		if (list != null && list.size() > 0) {
			for (ProcessDefinition pd : list) {
				// 获取部署ID
				String deploymentId = pd.getDeploymentId();
				deleteProcess(deploymentId);
			}
		}
	}

	/**
	 * 查询当前人的个人任务
	 * 
	 */
	public void findMyPersonalTask(String assignee) {
		List<Task> list = taskService// 与正在执行的任务管理相关的Service
				.createTaskQuery()// 创建任务查询对象
				.taskAssignee(assignee)// 指定个人任务查询，指定办理人
				.list();
		if (list != null && list.size() > 0) {
			for (Task task : list) {
				System.out.println("任务ID:" + task.getId());
				System.out.println("任务名称:" + task.getName());
				System.out.println("任务的创建时间:" + task.getCreateTime());
				System.out.println("任务的办理人:" + task.getAssignee());
				System.out.println("流程实例ID：" + task.getProcessInstanceId());
				System.out.println("执行对象ID:" + task.getExecutionId());
				System.out.println("流程定义ID:" + task.getProcessDefinitionId());
				System.out.println("########################################################");
			}
		}
	}

	/**
	 * 完成我的任务
	 */
	public void completeMyPersonalTask(String taskId) {
		taskService.complete(taskId);// 与正在执行的任务管理相关的Service
		System.out.println("完成任务：任务ID：" + taskId);
	}
	
	/**
	 * 已办任务列表
	 * 
	 * @param userId
	 * @param pageable
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<HistoricTaskInstance> findDoneTask(String userId, Pageable pageable) {
		List<HistoricTaskInstance> hpis = historyService.createHistoricTaskInstanceQuery().taskAssignee(userId).finished().orderByTaskCreateTime().desc().list();
		return hpis;
	}

	/**
	 * 办结任务列表
	 * 
	 * @param userId
	 * @param pageable
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<HistoricTaskInstance> findFinishedTask(String userId, Pageable pageable) {
	/*	List<HistoricTaskInstance> hpis = historyService.createHistoricTaskInstanceQuery().task(userId).finished().orderByTaskCreateTime().desc()
				.list();*/
		return null;
	}
}
